package com.gopay.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 
 * @MapUtil.java
 * @author zhanglei
 * @2013-8-22 下午5:21:24 www.gopay.com.cn Inc.All rights reserved.
 */
public class MapUtil {

    /**
     * 快速构造HashMap<br>
     * MapUtil.getStrMap("a", "12", "b", "345") = {a=12, b=345}<br>
     * 注：参数必须是偶数个
     */
    public static final Map<String, Object> get(String... params) {
        Map<String, Object> m = new HashMap<String, Object>();
        if (null == params) {
            return m;
        }
        if (0 == params.length) {
            return m;
        }
        if (params.length % 2 != 0) {
            // 参数长度必须是偶数
            throw new RuntimeException("The length of params must be even! params.length = " + params.length);
        }
        for (int i = 0; i < params.length; i = i + 2) {
            m.put(params[i], params[i + 1]);
        }
        return m;
    }

    /**
     * 使用 Map按key进行排序
     * @author wangdong
     * @param map
     * @return
     */
    public static String sortStringByKey(Map<String, String> map,String charActer) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<>(new Comparator<String>(){

            @Override
            public int compare(String str1, String str2) {
                return str1.compareTo(str2);
            }
        });
        sortMap.putAll(map);

        StringBuffer sb = new StringBuffer();
        for(Map.Entry<String,String> entry : sortMap.entrySet()){
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            sb.append(charActer);
        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }


    /**
     * 移除值为空的数据项
     * @author wangdong
     * @param map
     * @return
     */
    public static Map<String,String> removeNull(Map<String,String> map){

        Map<String,String> resultMap = new HashMap<>();

        for(Map.Entry<String,String> entry : map.entrySet()){
            if(StringUtils.isNotBlank(entry.getValue())){
                resultMap.put(entry.getKey(), entry.getValue());
            }
        }
        return resultMap;
    }
}
